package com.lanmaoly.cunzheng.thread;

public class InstanceSync extends Thread {
    public static void main(String[] args) throws Exception {
        // 临界区：多线程并发访问该资源
        final User user = new User();
        //对象锁
        final Object obj = new Object();
        // 线程1
        Thread t1 = new Thread() {
            @Override
            public void run() {
                synchronized (obj) {
                    user.setUsername("jack");
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    user.setPassword("123");
                }

            }
        };
        // 线程2
        Thread t2 = new Thread() {
            @Override
            public void run() {
                synchronized (obj) {
                    user.setUsername("rose");
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    user.setPassword("456");
                }
            }
        };

        //开启线程
        t2.start();
        t1.start();

        //等待两个线程都执行完，打印list结果
        t1.join();
        t2.join();

        //打印结果
        System.out.println(user);
    }
}